<template>
    <nly-content-wrapper class="a-base-container">
        <div class="wh100 resize-table-container" style="padding:10px;">
            <a-tabs class="wh100" defaultActiveKey="0" @change="changeTab">

                <a-tab-pane class="wh100" tab="账套管理" key="1">
                    <div class="inner-container wh100 table-container">

                        <a-card class="left-tree">
                            <a-tree :tree-data="yearData" @select="onSelect" default-expand-all :selectedKeys.sync="selectedYearKeys"></a-tree>
                        </a-card>
                        <div class="right-data">
                            <!-- 账套基本信息 -->
                            <a-card title="账套基本信息">
                                <template slot="extra">
                                    <a-button v-if="!accountList.some(f=>f.status < 2)" type="primary" @click="eidtAccouontFun" icon="plus">新增</a-button>
                                    <a-button v-else-if="currentAccount.id" type="primary" @click="eidtAccouontFun" icon="edit">编辑</a-button>
                                </template>
                                <a-row class="form-inline">
                                    <a-col :xs="24" :sm="24" :md="12" :lg="10" :xl="8" v-for="(item,index) in accountColumns" :key="index">
                                        <form-show :title="item.title" labelStyle="" rightStyle="width:180px;" class="ml-1 mb-2" :value="currentAccount[item.dataIndex]">
                                        </form-show>
                                    </a-col>

                                </a-row>
                            </a-card>
                            <!-- 会计期间信息 -->
                            <a-card title="会计期间" class="mt-4">
                                <template slot="extra">
                                    <a-button v-if="currentAccount.erpPeriodList && currentAccount.erpPeriodList.length == 0" type="primary" @click="AddAccounting" icon="plus">新增</a-button>
                                    <a-button v-else-if="currentAccount.erpPeriodList && currentAccount.erpPeriodList.length > 0" class="ml-2" type="primary" @click="EditAccountingFun" icon="edit">编辑</a-button>
                                </template>
                                <a-table class="middle-table" :columns="columns" :pagination="false" :data-source="erpPeriodList || []" :scroll="scroll" bordered>

                                </a-table>
                            </a-card>
                        </div>
                    </div>
                </a-tab-pane>
                <a-tab-pane class="wh100" tab="账户启用" key="2" style="display:flex;">
                    <enabled style="margin:0px;padding-top:0px;"></enabled>
                </a-tab-pane>
                <a-tab-pane class="wh100" tab="编码规则" key="3">
                    <a-table class="a-base-table wh100" :columns="ruleColumns" :pagination="false" :data-source="ruleDataSource" :loading="loading" :scroll="scroll" bordered>
                    </a-table>
                    <a-button type="primary" style="margin-left:15px" size="large" @click="saveRule" icon="save">保存</a-button>
                </a-tab-pane>

            </a-tabs>
        </div>
        <editAccounting ref="editAccounting" @ok="editAccountingOk"></editAccounting>
        <accountEdit ref="editAccount" @ok="editAccountOk"></accountEdit>
    </nly-content-wrapper>
</template>
<script>
import moment from "moment";
import dataMixins from "@/mixins/dataMixins";

import {
    list as listAccount
} from "@/api/erp/account";
import { list as ListPeriod, deleteLastYear } from "@/api/erp/period";
import {
    list as ListGradeRule,
    save as SaveGradeRule
} from "@/api/erp/gradeRule";
const editAccounting = () => import("./model/editAccounting");
const accountEdit = () => import("./model/accountEdit");

export default {
    // mixins: [dataMixins],
    components: {
        enabled: () => import("./enabled"),
        editAccounting,
        accountEdit
    },
    data () {
        //账套基本信息 字段
        let accountColumns = [
            { title: "账套年度", width: 140, dataIndex: "accountYear" },
            { title: "启用期间", width: 140, dataIndex: "enableDuration" },
            { title: "账套名称", width: 140, dataIndex: "accountName" },
            { title: "开始日期", width: 140, dataIndex: "beginDate" },
            { title: "结束日期", width: 140, dataIndex: "endDate" },
            { title: "法人代表", width: 140, dataIndex: "legalPerson" },
            { title: "单位名称", width: 140, dataIndex: "companyName" },
            { title: "邮政编码", width: 140, dataIndex: "postalCode" },
            { title: "企业类型", width: 140, dataIndex: "companyType" },
            { title: "行业性质", width: 140, dataIndex: "companyIndustry" },
            { title: "联系电话", width: 140, dataIndex: "contactNumber" },
            { title: "行政区", width: 140, dataIndex: "areaName" },
            { title: "开户银行", width: 140, dataIndex: "openingBank" },
            { title: "纳税地区", width: 140, dataIndex: "taxArea" },
            { title: "社会统一代码", width: 140, dataIndex: "unifiedSocialCode" },
            { title: "纳税性质", width: 140, dataIndex: "taxNature" },
            { title: "税率", width: 140, dataIndex: "taxRate" },
            { title: "备注", width: 140, dataIndex: "remarks" },
            { title: "账套主管", width: 140, dataIndex: "accountMasterName" }
        ];
        return {
            accountColumns, //账套基本信息 字段
            accountList: [], //账套 信息
            accountMap: new Map(), //账套 Map
            currentAccount: {}, //当前 账套



            //输入框布局
            formItemLayout: {
                labelCol: { span: 6 },
                wrapperCol: { span: 18 }
            },
            //其他布局
            formItemLayoutOther: {
                labelCol: { span: 10 },
                wrapperCol: { span: 14 }
            },

            //会计年份数据
            yearData: [
                {
                    title: "账套年份",
                    key: "0",
                    children: [
                        // { title: "2019", key: "2019" },
                        // { title: "2020", key: "2020" }
                    ]
                }
            ],
            //会计期间 Map
            periodMap: new Map(),
            //当前年份
            year: moment().format("YYYY"),
            //当前选择的年度
            selectedYearKeys: [],
            //当前选择的年度 会计期间
            erpPeriodList: [],
            currentErpPeriodVo: {},
            //表格滚动条
            scroll: { y: 500, x: 500 },
            //会计期间 表头信息
            columns: [
                {
                    title: "期间",
                    width: 140,
                    dataIndex: "currentPeriod",
                    customRender: (text, row, index) => {
                        return text + "月";
                    }
                },
                {
                    title: "起始日期",
                    width: 140,
                    dataIndex: "beginDate"
                },
                {
                    title: "结束日期",
                    width: 140,
                    dataIndex: "endDate"
                }
            ],
            //编码规则数据
            ruleDataSource: [
                { project: "科目编码级次", maxLength: "40" },
                { project: "物料分类编码级次", maxLength: "12" },
                { project: "结算方式编码级次", maxLength: "3" },
                { project: "货位编码级次", maxLength: "20" },
                { project: "收发类别编码级次", maxLength: "5" }
            ],
            // 编码规则标题
            ruleColumns: [
                {
                    title: "项目",
                    width: 200,
                    dataIndex: "title"
                },
                {
                    title: "最大长度",
                    dataIndex: "maxLen",
                    width: 60,
                    customRender: (text, record) => {
                        const key = "maxLen";
                        const change = e => {
                            record[key] = e.target.value;
                        };
                        return <a-input value={record[key]} onChange={change}></a-input>;
                    }
                },
                {
                    title: "第1级",
                    dataIndex: "level1",
                    width: 80,
                    customRender: (text, record) => {
                        return (
                            <a-input
                                value={(record.level && record.level[0]) || ""}
                                onChange={e => this.onChangeRuleLevel(e, record, 0)}
                            ></a-input>
                        );
                    }
                },
                {
                    title: "第2级",
                    dataIndex: "level2",
                    width: 80,
                    customRender: (text, record) => {
                        return (
                            <a-input
                                value={(record.level && record.level[1]) || ""}
                                onChange={e => this.onChangeRuleLevel(e, record, 1)}
                            ></a-input>
                        );
                    }
                },
                {
                    title: "第3级",
                    dataIndex: "level3",
                    width: 80,
                    customRender: (text, record) => {
                        return (
                            <a-input
                                value={(record.level && record.level[2]) || ""}
                                onChange={e => this.onChangeRuleLevel(e, record, 2)}
                            ></a-input>
                        );
                    }
                },
                {
                    title: "第4级",
                    dataIndex: "level4",
                    width: 80,
                    customRender: (text, record) => {
                        return (
                            <a-input
                                value={(record.level && record.level[3]) || ""}
                                onChange={e => this.onChangeRuleLevel(e, record, 3)}
                            ></a-input>
                        );
                    }
                },
                {
                    title: "第5级",
                    dataIndex: "level5",
                    width: 80,
                    customRender: (text, record) => {
                        return (
                            <a-input
                                value={(record.level && record.level[4]) || ""}
                                onChange={e => this.onChangeRuleLevel(e, record, 4)}
                            ></a-input>
                        );
                    }
                },
                {
                    title: "第6级",
                    dataIndex: "level6",
                    width: 80,
                    customRender: (text, record) => {
                        return (
                            <a-input
                                value={(record.level && record.level[5]) || ""}
                                onChange={e => this.onChangeRuleLevel(e, record, 5)}
                            ></a-input>
                        );
                    }
                },
                {
                    title: "第7级",
                    dataIndex: "level7",
                    width: 80,
                    customRender: (text, record) => {
                        return (
                            <a-input
                                value={(record.level && record.level[6]) || ""}
                                onChange={e => this.onChangeRuleLevel(e, record, 6)}
                            ></a-input>
                        );
                    }
                },
                {
                    title: "第8级",
                    dataIndex: "level8",
                    width: 80,
                    customRender: (text, record) => {
                        return (
                            <a-input
                                value={(record.level && record.level[7]) || ""}
                                onChange={e => this.onChangeRuleLevel(e, record, 7)}
                            ></a-input>
                        );
                    }
                },
                {
                    title: "第9级",
                    dataIndex: "level9",
                    width: 80,
                    customRender: (text, record) => {
                        return (
                            <a-input
                                value={(record.level && record.level[8]) || ""}
                                onChange={e => this.onChangeRuleLevel(e, record, 8)}
                            ></a-input>
                        );
                    }
                }
            ],
            //账套主管信息
            accMaster: {},
            //标签切换的下标
            tabKeys: 0,
            isShow: false
        };
    },
    created () {
        this.selectedYearKeys = [this.year + ""];
    },
    mounted () {
        this.ListAccount();
    },
    computed: {},
    methods: {
        //修改 编码规则 级次数据
        onChangeRuleLevel (e, record, index) {
            e.target.value = e.target.value.replace(/^(0+)|[^\d]+/g, "");
            let value = e.target.value;
            console.log("onChangeRuleLevel", value, record, index);
            if (!index && 0 != index) {
                setTimeout(() => {
                    e.target.value = record.level[index] || "";
                }, 500);
                return false;
            }
            value = parseInt(value);
            //获取最大编码长度
            let maxLength = parseInt(record.maxLen);
            let level = record.level;
            if (!level) {
                if (value > maxLength) {
                    this.$message.error("编码级次总长度不能大于最大长度");
                    setTimeout(() => {
                        e.target.value = record.level[index] || "";
                    }, 500);
                    return false;
                } else {
                    record.level = [value];
                }
            } else {
                let total = value;
                level.forEach &&
                    level.forEach((item, i) => {
                        if (item && i != index) {
                            total += parseInt(item);
                        }
                    });
                console.log("total > maxLength", total, maxLength, total > maxLength);
                if (total > maxLength) {
                    this.$message.error("编码级次总长度不能大于最大长度");
                    setTimeout(() => {
                        e.target.value = record.level[index] || "";
                    }, 500);
                    return false;
                } else {
                    record.level[index] = value;
                }
            }
        },
        //标签切换调用
        changeTab (key) {
            console.log(key);
            this.tabKeys = key;
            if (key == 3) {
                this.loadRuleList();
            }
        },

        // 获取 账套信息
        ListAccount () {
            const { accountMap, year } = this;
            listAccount()
                .then(response => {
                    if (response.code === 200) {
                        const { data } = response;
                        this.accountList = data;
                        let yearDataChildren = [];
                        data.forEach(item => {
                            accountMap.set(item.accountYear, item);
                            yearDataChildren.push({
                                title: item.accountYear + "",
                                key: item.accountYear + ""
                            });
                        })
                        this.$set(this.yearData[0], "children", yearDataChildren);
                        this.selectedYearKeys = [this.year + ""];
                        this.currentAccount = accountMap.get(year * 1) || {};
                        this.erpPeriodList = this.currentAccount.erpPeriodList || [];
                    }
                })
                .catch(error => { });
        },
        //新增/编辑 账套基本信息
        eidtAccouontFun () {
            const { currentAccount, accountList } = this;
            // if (null == currentAccount) this.$message.warning("请选择年份");
            this.$refs.editAccount.isFirstYear = !accountList.length;
            this.$refs.editAccount.postData = { ...currentAccount };
            this.$refs.editAccount.initData();
            this.$refs.editAccount.visible = true;
        },
        //保存成功后刷新
        editAccountOk () {
            this.ListAccount();
        },
        //当点击数的节点时，切换表格数据
        onSelect (selectedKeys, info) {
            const { accountMap, periodMap } = this;
            this.currentAccount = accountMap.get(selectedKeys[0] * 1) || {};
            this.erpPeriodList = this.currentAccount.erpPeriodList || [];
            // this.currentErpPeriodVo = periodMap.get(selectedKeys[0] * 1) || {};
            this.selectedYearKeys = selectedKeys;
            console.log("selected", selectedKeys, this.selectedYearKeys, info);
        },
        check () {
            this.form.validateFields(err => {
                if (!err) {
                    console.info("success");
                }
            });
        },

        //添加 会计期间
        AddAccounting: function () {
            const { currentAccount } = this;
            let data = {
                title: "会计期间-新增",
                currentAccount
            };
            Object.assign(this.$refs.editAccounting, { ...data });
            this.$refs.editAccounting.add();
        },
        //编辑 会计期间
        EditAccountingFun () {
            const { erpPeriodList, currentAccount } = this;
            let data = {
                title: "会计期间-编辑",
                currentAccount
            };
            Object.assign(this.$refs.editAccounting, { ...data });
            let newErpPeriodList = erpPeriodList.map(item => { return { ...item } });
            this.$refs.editAccounting.edit(newErpPeriodList);
        },
        // 保存会计期间 成功后 的 callback
        editAccountingOk () {
            this.ListAccount();
        },
        // 删除 会计期间
        // deleteLastYear() {
        //   const { selectedYearKeys } = this;
        //   let lastYear = selectedYearKeys[0];
        //   if (!lastYear) {
        //     this.$message.warning("请选择年份");
        //     return false;
        //   }
        //   deleteLastYear({ lastYear })
        //     .then(response => {
        //       if (response.code === 200) {
        //         this.$message.success("删除成功");
        //         this.ListPeriod();
        //       }
        //     })
        //     .catch(error => {});
        // },

        //加载 编码规则
        loadRuleList (arg) {
            //加载数据 若传入参数1则加载第一页的内容
            if (arg === 1) {
                this.pagination.current = 1;
            }
            var params = {}; //查询条件
            this.loading = true;
            ListGradeRule(params).then(res => {
                console.log(res);
                if (res.code == 200) {
                    this.ruleDataSource = this.getRuleData(res.data);
                } else {
                    // this.$message.warning(res.message);
                }
                this.loading = false;
            });
        },
        //处理 编码规则数据
        getRuleData (data) {
            for (let j = 0; j < data.length; j++) {
                let level = data[j].codingRule.split("");
                data[j].level = level;
            }
            console.log(data);
            return data;
        },
        //保存 编码规则数据
        saveRule () {
            let data = Object.assign([], this.ruleDataSource);
            for (let i = 0; i < data.length; i++) {
                data[i].codingRule = data[i].level.filter(item => item).join("");
                delete data[i].level;
            }
            console.log(data);
            console.log(this.ruleDataSource);
            // return;
            SaveGradeRule(data).then(res => {
                console.log(res);
                if (res.code == 200) {
                    this.$message.success("保存成功");
                    this.loadRuleList();
                } else {
                    // this.$message.warning(res.message);
                }
            });
        }
    }
};
</script>
<style lang="less">
    .ant-tabs-content {
        height: calc(100% - 110px);
    }
    .middle-table {
        width: 700px;
        .ant-table-body {
            height: calc(100vh - 400px);
        }
    }

    .h3 {
        border-bottom: 1px solid #ddd;
        padding: 10px 0;
    }
    .table-container {
        display: flex;
        justify-content: flex-start;
    }
    .left-tree {
        width: 160px;
        padding: 0px;
        height: 100%;
        margin-right: 10px;
    }
    .right-data {
        width: calc(100% - 170px);
        overflow-y: scroll;
    }
</style>
 